<template>
	<view class="login-container">
		<!-- 提示登录图标 -->
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<!-- 登录按钮 -->
		<button type="primary" class="btn-login" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button>
		<!-- 登录提示 -->
		<view class="tips-text">登录后尽享更多权益</view>
		
	</view>
</template>

<script>
	
	import { compile } from 'vue';
import {mapMutations,mapState} from 'vuex'
	export default {
		name:"my-login",
		data() {
			return {
				
			};
		},
		computed:{
			...mapState('m_user',['redirectInfo'])
		},
		methods:{
			
			...mapMutations('m_user',['updateUserInfo','updateToken','updateRedirectInfo']),
			
			
			getUserInfo(e){
				if(e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMessage('您取消了登录授权')
			
				// console.log(e.detail)
				this.updateUserInfo(e.detail.userInfo)
				
				//获取登录成功后的token字符串
				this.getToken(e.detail)
			},
			
			async getToken(info){
				//调用微信登录接口
				const res = await uni.login().catch(err=>err)
				// console.log(res)
				if(res.errMsg !== 'login:ok') return uni.$showMessage('登录失效!')
				//准备参数对象
				const query = {
					code:res.code,
					encryptedData:info.encryptedData,
					iv:info.iv,
					rawData:info.rawData,
					signature:info.signature
				}
				const {data:loginResult} =  await uni.$http.post('/api/public/v1/users/wxlogin',query)
				// console.log(loginResult)
				if(loginResult.meta.status!==400) return uni.$showMessage('登录失败!')
				// uni.$showMessage('登录成功')
				const token = 'Bearer asdfghjkl'
				this.updateToken(token)
				//判断vuex中的redirectInfo是否为null
				//如果不为null，在登录之后跳转回之前的页面
				this.navigateBack()
				
			},
			
			navigateBack(){
				//redirect不为null，并且导航方式为switchTab
				if(this.redirectInfo && this.redirectInfo.openType ==='switchTab'){
					uni.switchTab({
						url:this.redirectInfo.from,
						complete:()=>{
							//导航完成后把redirectInfo重置为null
							this.updateRedirectInfo(null)
						}
					})
					
				}
			}
		}
	}
</script>

<style lang="scss">
	
	.login-container{
		height: 750rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		position: relative;
		background-color: #e8e8e8;
		// 超过盒子的布局部分隐藏
		overflow: hidden;
		
		//伪元素布局
		&::after{
			content: ' ';
			display: block;
			width: 100%;
			height: 40px;
			position: absolute;
			bottom: 0;
			left: 0;
			background-color: white;
			border-radius: 100%;
			transform: translateY(50%);
		}
		
		.btn-login{
			 width: 90%;
			 background-color: #C00000;
			 border-radius: 100px;
			 margin: 15px 0;
		}
		
		.tips-text{
			font-size: 12px;
			color: gray;
		}
		
	}

</style>